package cn.whx.hrm.userdetails;

import cn.whx.hrm.client.UserInfoClient;
import cn.whx.hrm.constant.AuthConstant;
import cn.whx.hrm.domain.LoginUser;
import cn.whx.hrm.domain.UserContextInfo;
import cn.whx.hrm.mapper.LoginUserMapper;
import cn.whx.hrm.util.AjaxResult;
import cn.whx.hrm.util.ValidUtils;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import cn.whx.hrm.domain.Permission;
import springfox.documentation.spring.web.json.Json;

import java.util.ArrayList;
import java.util.List;

@Service
public class HrmUserDetailsService implements UserDetailsService {
    @Autowired
    private LoginUserMapper loginUserMapper;
    @Autowired
    private UserInfoClient userInfoClient;
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(username);
        loginUser = loginUserMapper.selectOne(loginUser);
        System.out.println(loginUser);
        //判断用户是否存在
        ValidUtils.assertNotNull(loginUser, "用户不存在");
        //用户存在查询它的每个权限
        List<Permission> list =  loginUserMapper.loadUserPermissionById(loginUser.getId());
        ArrayList<GrantedAuthority> arrayList = new ArrayList<>();
        //遍历交给security
        list.stream().forEach(permission -> {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(permission.getSn());
            arrayList.add(simpleGrantedAuthority);
        });
        //判断是不是管理员 如果是就可以获取其他信息
        if (loginUser.getType() == 0){
            AjaxResult result = userInfoClient.getUserInfo(loginUser.getId());
            if (!result.isSuccess()){
                throw new RuntimeException(result.getMessage());
            }
            //获取里面的相关信息
            Object obj = result.getResultObj();
            //判断非空
            ValidUtils.assertNotNull(obj, "不是管理员");
            //转换成josn格式
            String jsonString = JSON.toJSONString(obj);
            //把JSON转换成java
            UserContextInfo userContextInfo = JSON.parseObject(jsonString, UserContextInfo.class);
            String key = AuthConstant.USER_INFO_KEY + loginUser.getUsername();
            redisTemplate.opsForValue().set(key,userContextInfo );

        }
        return new User(loginUser.getUsername(),loginUser.getPassword(),arrayList);
    }
}
